package qingke.struts.example.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.query.Query;

import qingke.struts.example.model.User;

public class UserDao {
	
	private SessionFactory sf=null;
	private Session session =null;
	
	public UserDao(){
		
	}
	
	{
		sf=new Configuration().configure().buildSessionFactory();
		session=sf.openSession();
	}
    
	
	public Criteria getCriteria(Class<?> classType){
		DetachedCriteria detachedCriteria =DetachedCriteria.forClass(classType);
		Criteria criteria=detachedCriteria.getExecutableCriteria(session);
		return criteria;
	}
	
	public void insert(User user){
		Transaction tx=session.beginTransaction();
		try{
			session.save(user);
			tx.commit();		
		}catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	
	public void update(User user){
		Transaction tx=session.beginTransaction();
		try{
			session.update(user);
			tx.commit();		
		}catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void delete(User user){
		Transaction tx=session.beginTransaction();
		try{
			session.delete(user);
			tx.commit();		
		}catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public List<User> getAllUser(){
	    Query<User> query=session.createQuery("from User",User.class);
	    return query.getResultList();
	}
	
}
